package tv.danmaku.ijk.app.wdget;

import android.content.Context;

import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



import java.io.IOException;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class MyPlayer extends FrameLayout {

    private static final boolean DEBUG = true;

    private SurfaceView mSurfaceView;

    private boolean haveViewHoudler = false;
    private boolean isPreparePlayer = false;

    private OPTION_STATUS option_status = OPTION_STATUS.STOP;

    private String mUrl = null;

    private IMediaPlayer mediaPlayer = null;
    private ControlPlayView controlPlayView;



    public MyPlayer (@NonNull Context context) {
        super(context);
        init();
    }

    public MyPlayer (@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyPlayer (@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    //============================================================================
    //  视图配置
    //============================================================================

    private void init () {
        // init player
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");

        //  配置显示控件

        mSurfaceView = new SurfaceView(getContext());
//        mSurfaceView.setZOrderMediaOverlay(true);
        MarginLayoutParams params = new MarginLayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mSurfaceView.setLayoutParams(params);
        mSurfaceView.getHolder().addCallback(surfaceCallBack);
        addView(mSurfaceView);

        controlPlayView = new ControlPlayView(getContext());
        params = new MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        controlPlayView.setLayoutParams(params);
        addView(controlPlayView);


    }


    //============================================================================
    //  主要流程
    //============================================================================

    private void preparePlayer () {
        if (mediaPlayer == null) {
            Log("preparePlayer");
            // 配置播放控件
            IjkMediaPlayer ijkMediaPlayer = new IjkMediaPlayer();
            mediaPlayer = ijkMediaPlayer;
            try {
                mediaPlayer.setDataSource(mUrl);
            } catch (IOException e) {
                Log(" 加载资源出现异常 " + e.toString());
                e.printStackTrace();
            }

//            ijkMediaPlayer.setOption("analyzeduration", "2000000");
//            ijkMediaPlayer.setOption("fflags", "nobuffer");
//            ijkMediaPlayer.setOption("probsize", "4096");

//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 1);
//
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", IjkMediaPlayer.SDL_FCC_RV32);
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1);
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);
//
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "http-detect-range-support", 1);
//
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48);
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "min-frames", 100);
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
//
//            ijkMediaPlayer.setVolume(1.0f, 1.0f);
//
//            int value = 0; // 是否开启硬解码
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", value);//开启硬解码
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", value);
//            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", value);

            ijkMediaPlayer.setOnPreparedListener(onPreparedListener);
            ijkMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
            ijkMediaPlayer.setOnCompletionListener(mCompletionListener);
            ijkMediaPlayer.setOnInfoListener(mInfoListener);
            ijkMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
            ijkMediaPlayer.setOnErrorListener(mErrorListener);
            ijkMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);

            ijkMediaPlayer.prepareAsync();

        }
    }

    enum OPTION_STATUS {
        START,
        PAUSE,
        STOP
    }

    //============================================================================
    //  对外操作
    //============================================================================

    public void setUrl (String url) {
        mUrl = url;
    }

    public void start () {

        controlPlayView.setPlayStatus(ControlPlayView.PLAY_STATUS.CACHING);

        option_status = OPTION_STATUS.START;
        if (mUrl == null) {
            Toast.makeText(getContext(), "请先设置URL", Toast.LENGTH_SHORT).show();
        }

        preparePlayer();

        Log("start  " + haveViewHoudler + "    " + isPreparePlayer);
        if (haveViewHoudler && isPreparePlayer) {
            mediaPlayer.setDisplay(mSurfaceView.getHolder());
            mediaPlayer.start();
        }
    }

    public void pause () {
        option_status = OPTION_STATUS.PAUSE;
    }

    public void stop () {
        option_status = OPTION_STATUS.STOP;
        mediaPlayer.stop();
        mediaPlayer.reset();
        mediaPlayer.release();

        isPreparePlayer = false;

        mediaPlayer = null;
    }

    public void setViewControllerListener(ControlPlayView.ViewControllerListener viewControllerListener){
        controlPlayView.setViewControllerListener(viewControllerListener);
    }

    public boolean isShowOption(){
        return controlPlayView.isShowOption();
    }

    //============================================================================
    //  事件响应
    //============================================================================


    private SurfaceHolder.Callback surfaceCallBack = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated (SurfaceHolder holder) {
            Log("surfaceCreated");
            haveViewHoudler = true;
            if (option_status == OPTION_STATUS.START) {
                start();
            }

        }

        @Override
        public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {
            Log("surfaceChanged");
            haveViewHoudler = true;
        }

        @Override
        public void surfaceDestroyed (SurfaceHolder holder) {
            Log("surfaceDestroyed");
            haveViewHoudler = false;

        }
    };

    private IMediaPlayer.OnPreparedListener onPreparedListener = new IMediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared (IMediaPlayer mp) {
            Log("onPrepared");
            isPreparePlayer = true;
            if (option_status == OPTION_STATUS.START) {
                start();
                controlPlayView.setPlayStatus(ControlPlayView.PLAY_STATUS.PLAYING);
            }
        }
    };


    IMediaPlayer.OnVideoSizeChangedListener mSizeChangedListener =
            new IMediaPlayer.OnVideoSizeChangedListener() {
                public void onVideoSizeChanged (IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {
//                    Log("onVideoSizeChanged");
                }
            };


    private IMediaPlayer.OnCompletionListener mCompletionListener =
            new IMediaPlayer.OnCompletionListener() {
                public void onCompletion (IMediaPlayer mp) {
                    Log("onCompletion");
                }
            };

    private IMediaPlayer.OnInfoListener mInfoListener =
            new IMediaPlayer.OnInfoListener() {
                public boolean onInfo (IMediaPlayer mp, int arg1, int arg2) {
//                    Log("onInfo");
                    return true;
                }
            };

    private IMediaPlayer.OnErrorListener mErrorListener =
            new IMediaPlayer.OnErrorListener() {
                public boolean onError (IMediaPlayer mp, int framework_err, int impl_err) {
                    controlPlayView.setPlayStatus(ControlPlayView.PLAY_STATUS.ERROR);
                    return true;
                }
            };

    private IMediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
            new IMediaPlayer.OnBufferingUpdateListener() {
                public void onBufferingUpdate (IMediaPlayer mp, int percent) {
//                  Log("onBufferingUpdate");
                }
            };

    private IMediaPlayer.OnSeekCompleteListener mSeekCompleteListener = new IMediaPlayer.OnSeekCompleteListener() {

        @Override
        public void onSeekComplete (IMediaPlayer mp) {
            Log("onSeekComplete");
        }
    };


    //============================================================================
    //  其他工具函数
    //============================================================================



    private void Log (String msg) {
        if (DEBUG)
            Log.i("result", msg);
    }

}
